/**
 * Created by hylin on  2014/7/16.
 * 车辆监控页面
 */
var monitorPage = function(){
    var map = null,
        data = [],
        markers = {},
        openedDeviceImei = null,//当前打开信息窗口的设备imei
        infowindow = null,
        infowindowDom = null,//为了避免setContent引起闪动，所以保存一份content的句柄
        firstLoad = true,
        params = goome.wx.utils.defaultParams(),
        refreshTime = 10000,//定时刷新时间
        countdown = refreshTime / 1000,
        countdownTimer = null,
        $header = $('.header'),
        headerHeight = $header.height(),
        $monitorBtn = $('.toolbox',$header),
        $infobar = $('.info-bar',$header),
        $refreshBtn = $('.refresh-btn'),
        $countdown = $('.countdown .seconds',$infobar),
        $deviceChanger = $('#device-changer'),
        $mapContainer = $('#map-container');

    params.map_type = 'BAIDU';

    function loadData(){ //加载数据
        $.when(getRemoteData('account/devinfo'),getRemoteData('account/monitor'))
            .done(function(results1, results2){
                results1 = results1[0];
                results2 = results2[0];
                if(results1.errcode === 0 && results2.errcode === 0){
                    data = mergeData(results1.data, results2.data);
                    filterData(); //过滤data
                    renderMap();//渲染地图
                }else{
                    if(results1.errcode != 0) {
                        goome.wx.utils.showTip(results1);
                    }else{
                        goome.wx.utils.showTip(results2);
                    }
                }
            });
        startCountdown();//开启倒计时
    }
    function getRemoteData(url){ //获取远程数据
        return $.ajax({
            url: goome.wx.config.apiUrl+url,
            data: params,
            dataType: 'jsonp',
            success: function(results){

            },
            error: function(err){
                goome.wx.utils.showTip(err);
            }
        });
    }
    function filterData(){ //过滤data
        data = $.grep(data, function(v,i){
            return (v.device_info_new == 0 || v.device_info_new == 3 ||v.device_info_new == 4);
        });
    }
    //合并基本信息和实时信息
    function mergeData(list1, list2){
        $.each(list1, function(i,v){
            $.each(list2, function(j, o){
                if(v.imei == o.imei){
                    $.each(o, function(k, p){
                        v[k] = p;
                    });
                    return false;
                }
            });
        });
        return list1;
    }
    function renderMap(){ //渲染地图
        var points = [],
            tempData = null;
        $.each(data, function(i, v){
            if(markers[v.imei]){
                var icon = new BMap.Icon('images/'+(v.device_info_new == 0?'car_green.png':'car_gray.png'), new BMap.Size(32,32));
                markers[v.imei].setIcon(icon);//自定义图标
                markers[v.imei].setPosition(new BMap.Point(v.lng, v.lat));
                //百度地图没有开放icon的样式设置api，这里找到iconDom直接修改，使用旋转来解决车辆方向显示
                $(markers[v.imei].iconDom).css({
                    '-webkit-transform': 'rotate('+v.course+'deg)',//方法旋转画布的坐标系统。
                    'transform': 'rotate('+v.course+'deg)'//指定对象的2D rotation（2D旋转）
                });
            }else {
                createMarker(v);
            }
            points.push(new BMap.Point(v.lng, v.lat));
            if(!openedDeviceImei){//打开设备的IMEI
                openedDeviceImei = v.imei;
            }
            if(openedDeviceImei == v.imei){//我关注的那个open
                tempData = v;
            }
        });
        if(firstLoad){
            map.setViewport(points);
            points = null;
        }
        if(openedDeviceImei && tempData){
            updateContent(tempData);//更新内容
            infowindow.open(markers[openedDeviceImei].getPosition());
        }
        //第一次加载数据需要将信息窗口自动移动，后续则取消
        if(firstLoad){
            firstLoad = false;
            infowindow.disableAutoPan();
        }
    }

    function updateContent(data) { //更新内容
        var status = goome.wx.config.status[data.device_info_new] + (data.device_info_new == 0 ? (data.speed + '&nbsp;&nbsp;km/h') : '');
        infowindowDom.find('.status').html(status);
        infowindowDom.find('.name').text(data.name || '');
        goome.wx.utils.getAddress(data.lng, data.lat, function (address) {
            infowindowDom.find('.address').text(address);
            //自动调整信息窗口的高度
            infowindowDom.height(infowindowDom.find('.content').height());
        });
        //手动修改各个连接href
        infowindowDom.find('.js-track').attr('href','track.html?'+goome.wx.utils.serialize()+'&imei='+data.imei+'&name='+data.name+'&devtype='+data.dev_type);
        infowindowDom.find('.js-playback').attr('href','playback.html?'+goome.wx.utils.serialize()+'&imei='+data.imei+'&name='+data.name);
        infowindowDom.find('.js-info').attr('href','info.html?'+goome.wx.utils.serialize()+'&imei='+data.imei+'&lng='+data.lng+'&lat='+data.lat);
        $infobar.find('.time').text(goome.wx.utils.dateFormat(data.gps_time) || '');
        $infobar.find('.name').text(data.name || '');
    }

    function refresh(){
        loadData();
    }
    function startCountdown() { //右上角计时
        clearInterval(countdownTimer);
        countdown = refreshTime / 1000;//10s
        $countdown.html(countdown);
        countdownTimer = setInterval(function () {
            if (countdown > 0) {
                $countdown.html(countdown);
            } else {
                clearInterval(countdownTimer);
                refresh();// 重新获取数据，清除计时
            }
            countdown--;
        }, 1000);
    }
    function pauseCountdown(){
        clearInterval(countdownTimer);
    }
    function createMarker(v){ //创建Marker
        var icon = v.device_info_new == 0?'car_green.png':'car_gray.png';
        var marker = new BMap.Marker(new BMap.Point(v.lng, v.lat), {
            icon: new BMap.Icon('images/'+icon, new BMap.Size(32,32))
        });//在point处添加标注
        map.addOverlay(marker);//添加覆盖物
        marker.addEventListener('click', markerShowInfo = function(e){
         var Marker = this;//点击标注的时候，为标注添加事件
            $.each(data, function(i, v){
                if(data[i].imei==Marker.imei){
                    updateContent(v);//更新文字内容
                    infowindow.open(e.target.getPosition());
                    openedDeviceImei = v.imei;
                }
            });
        });
        marker.imei = v.imei;
        setTimeout(function(){
            $(marker.iconDom).css({
                '-webkit-transform': 'rotate('+v.course+'deg)',
                'transform': 'rotate('+v.course+'deg)'
            });
        },20);

        markers[v.imei] = marker;
    }

    function openDevice(data){
        updateContent(data);
        infowindow.open(markers[data.imei]);
        openedDeviceImei = data.imei;
    }

    function changeDevice(action) {
        var seq = 0,
            len = data.length;
        $.each(data, function (i, v) {
            if (v.imei == openedDeviceImei) {
                seq = i;
                if (action == 'prev') {
                    seq--;
                    if(seq<0){
                        seq = len-1;
                    }
                } else if (action == 'next') {
                    seq++;
                    if(seq > len-1){
                        seq = 0;
                    }
                }
                openDevice(data[seq]);
                return false;
            }
        });
    }
    function getIOSWindowHeight() {
        // Get zoom level of mobile Safari
        // Note, that such zoom detection might not work correctly in other browsers
        // We use width, instead of height, because there are no vertical toolbars :)
        var zoomLevel = document.documentElement.clientWidth / window.innerWidth;

        // window.innerHeight returns height of the visible area.
        // We multiply it by zoom and get out real height.
        return window.innerHeight * zoomLevel;
    }
    function resize(){
        var winHeight = $.os.ios?getIOSWindowHeight():$(window).height();
        $mapContainer.height(winHeight - headerHeight);
    }

    function initMap(){
        var center = new BMap.Point(113.920787,22.573978);
        map = new BMap.Map('map-container');
        map.centerAndZoom(center, 5);
        map.addControl(new BMap.NavigationControl({
            anchor: BMAP_ANCHOR_TOP_RIGHT,
            type: BMAP_NAVIGATION_CONTROL_ZOOM,
            offset: new BMap.Size(0, 40)
        }));
        map.addControl(new BMap.ScaleControl({
            anchor: BMAP_ANCHOR_TOP_LEFT,
            offset: new BMap.Size(0, 40)
        }));
        map.enableScrollWheelZoom(true);

        var html = '<div class="info-window-container">' +
            '<div class="arrow"></div>' +
            '<ul class="content">' +
            '<li><span class="name"></span></li>' +
            '<li>'+wxLang.status+': <span class="status"></span></li>' +
            '<li>'+wxLang.address+': <span class="address"></span></li>' +
            '<li class="toolbar">' +
            '<a target="_self" class="js-track" href="track.html?'+goome.wx.utils.serialize()+'&imei=">'+wxLang.tracking+'</a><a target="_self" class="js-playback" href="playback.shtml?'+goome.wx.utils.serialize()+'&imei=">'+wxLang.playback+'</a><a target="_self" class="js-info" href="info.shtml?'+goome.wx.utils.serialize()+'&imei=">'+wxLang.info+'</a>' +
            '</li>' +
            '</ul></div>';
        infowindowDom = $(html);

        infowindow = new BMapLib.InfoBox(map, infowindowDom[0], {
            offset: new BMap.Size(0, 20),
            enableAutoPan: true,
            closeIconUrl: 'images/close.png',
            closeIconMargin: '-999px',//不需要关闭按钮，api未提供该开关，所以设置一个不可见的margin来达到隐藏目的
            align: INFOBOX_AT_TOP
        });
        //百度地图会绑定touch相关事件，导致信息窗口中的链接失效，无法点击。所以需要单独设置一下
        infowindowDom.on('touchstart MSPointerDown pointerdown','a', function(e){
            location.href = e.target.href;
        });
    }

    function bindEvents(){
        //百度地图会绑定touch相关事件，使zepto的tap失效，所以简单的用click
        //Android webview 下 click会触发两次的情况，可以使用goome.wx.utils.androidClickBug()解决
        //目前测试没发现什么问题，后续再看需不需要
        $deviceChanger.on('click', 'a', function(){
            changeDevice($(this).data('action'));
        });
        $monitorBtn.on('click', function(){
            var $this = $(this);
            if($this.data('pause')){
                $this.removeClass('pause').data('pause', false);
                startCountdown();
            }else{
                $this.addClass('pause').data('pause', true);
                pauseCountdown();
            }
        });
        $refreshBtn.on('click', function(e){
            loadData();
        });
    }

    function init(){
        bindEvents();
        resize();
        initMap();
        loadData();
    }
    return {
        init: init
    };
}();